import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material';
import { SelectionModel } from '@angular/cdk/collections';
import { AuthGuardService } from '../../service/AuthGuardService';
import { ForumService } from '../../service/ForumService';
import { ConfirmDialogComponent } from '../confirmDialog/confirmDialog';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { NewsCategory } from '../../models/NewsCategory';
import { environment } from '../../environments/environment';
import { filter } from 'rxjs/operators';
import {Location} from '@angular/common';
import {EditorComponent} from '../editor/editor';
import {UpdateTypeComponent } from '../updateType/updateType';
import { AddTypeComponent } from '../addType/addType';

@Component({
  templateUrl: './manageArticle.html',
  styleUrls: ['./manageArticle.css'],
})
export class ManageArticleComponent implements OnInit {
  selection: SelectionModel<NewsCategory>;
  cols = ['select', 'newsCategory', 'operate'];
  categorys: NewsCategory[];
  total: number;
  pageSize = environment.pageSize;
  page = 0;

  constructor(
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private router: Router,
    private location: Location,

    private authGuardService: AuthGuardService,
    private  forumService: ForumService
  ) { }

  ngOnInit() {
   this.getList();
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<NewsCategory>(allowMultiSelect, initialSelection);
  }
  getList() {
    this.forumService.getForumTypes().subscribe((res) => {
      this.categorys = res.res;
    })
  }
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.categorys.length;
    return numSelected === numRows;
  }

  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.categorys.forEach(row => this.selection.select(row));
  }

  onOpenAdd() {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(AddTypeComponent, {
        width: '600px',
        height: '700px',
        data: {
          categorys: this.categorys
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.getList();
      });
    });
  }

  onOpenEdit(category: NewsCategory) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(UpdateTypeComponent, {
        width: '600px',
        height: '700px',
        data: {
            categorys: category
        }
      });
      dialogRef.afterClosed().subscribe((result) => {

      });
    });
  }

  onDelete(id: number) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(ConfirmDialogComponent, {
        width: '400px',
        height: '200px',
        data: {message: '确认删除？'}
      });
      dialogRef.afterClosed().subscribe((result) => {
        if (result) {
          this.forumService.deleteCategory(id).subscribe((res) => {
            if (res.success) {
                  this.getList();
            }
          });
        }
      });
    });
  }

  update(event: {pageIndex: number, pageSize: number}) {
    this.forumService.getForums(event.pageIndex, event.pageSize).subscribe((res) => {
      this.categorys = res.res;
      this.total = res.total;
      this.page = event.pageIndex;
    });
  }

  goBack() {
    this.location.back();
  }

  trackById(index: number, item: any) {
    return item.id;
  }
}
// import {FlatTreeControl} from '@angular/cdk/tree';
// import {Component, Injectable} from '@angular/core';
// import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';
// import {BehaviorSubject, Observable, of as observableOf} from 'rxjs';
//
// /**
//  * File node data with nested structure.
//  * Each node has a filename, and a type or a list of children.
//  */
// export class FileNode {
//   children: FileNode[];
//   filename: string;
//   type: any;
// }
//
// /** Flat node with expandable and level information */
// export class FileFlatNode {
//   constructor(
//     public expandable: boolean, public filename: string, public level: number, public type: any) {}
// }
//
// /**
//  * The file structure tree data in string. The data could be parsed into a Json object
//  */
// const TREE_DATA = JSON.stringify({
//   Applications: {
//     Calendar: 'app',
//     Chrome: 'app',
//     Webstorm: 'app'
//   },
//   Documents: {
//     angular: {
//       src: {
//         compiler: 'ts',
//         core: 'ts'
//       }
//     },
//     material2: {
//       src: {
//         button: 'ts',
//         checkbox: 'ts',
//         input: 'ts'
//       }
//     }
//   },
//   Downloads: {
//     October: 'pdf',
//     November: 'pdf',
//     Tutorial: 'html'
//   },
//   Pictures: {
//     'Photo Booth Library': {
//       Contents: 'dir',
//       Pictures: 'dir'
//     },
//     Sun: 'png',
//     Woods: 'jpg'
//   }
// });
//
// /**
//  * File database, it can build a tree structured Json object from string.
//  * Each node in Json object represents a file or a directory. For a file, it has filename and type.
//  * For a directory, it has filename and children (a list of files or directories).
//  * The input will be a json object string, and the output is a list of `FileNode` with nested
//  * structure.
//  */
// @Injectable()
// export class FileDatabase {
//   dataChange = new BehaviorSubject<FileNode[]>([]);
//
//   get data(): FileNode[] { return this.dataChange.value; }
//
//   constructor() {
//     this.initialize();
//   }
//
//   initialize() {
//     // Parse the string to json object.
//     const dataObject = JSON.parse(TREE_DATA);
//
//     // Build the tree nodes from Json object. The result is a list of `FileNode` with nested
//     //     file node as children.
//     const data = this.buildFileTree(dataObject, 0);
//
//     // Notify the change.
//     this.dataChange.next(data);
//   }
//
//   /**
//    * Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object.
//    * The return value is the list of `FileNode`.
//    */
//   buildFileTree(obj: object, level: number): FileNode[] {
//     return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
//       const value = obj[key];
//       const node = new FileNode();
//       node.filename = key;
//
//       if (value != null) {
//         if (typeof value === 'object') {
//           node.children = this.buildFileTree(value, level + 1);
//         } else {
//           node.type = value;
//         }
//       }
//
//       return accumulator.concat(node);
//     }, []);
//   }
// }
//
// /**
//  * @title Tree with flat nodes
//  */
// @Component({
//   templateUrl:  './manageArticle.html',
//   styleUrls: ['./manageArticle.css'],
//   providers: [FileDatabase]
// })
// export class ManageArticleComponent {
//   treeControl: FlatTreeControl<FileFlatNode>;
//   treeFlattener: MatTreeFlattener<FileNode, FileFlatNode>;
//   dataSource: MatTreeFlatDataSource<FileNode, FileFlatNode>;
//
//   constructor(database: FileDatabase) {
//     this.treeFlattener = new MatTreeFlattener(this.transformer, this._getLevel,
//       this._isExpandable, this._getChildren);
//     this.treeControl = new FlatTreeControl<FileFlatNode>(this._getLevel, this._isExpandable);
//     this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
//
//     database.dataChange.subscribe(data => this.dataSource.data = data);
//   }
//
//   transformer = (node: FileNode, level: number) => {
//     return new FileFlatNode(!!node.children, node.filename, level, node.type);
//   }
//
//   private _getLevel = (node: FileFlatNode) => node.level;
//
//   private _isExpandable = (node: FileFlatNode) => node.expandable;
//
//   private _getChildren = (node: FileNode): Observable<FileNode[]> => observableOf(node.children);
//
//   hasChild = (_: number, _nodeData: FileFlatNode) => _nodeData.expandable;
// }